package cn.stylefeng.guns.modular.rec.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.model.params.BasicCarrierParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicCarrierResult;
import cn.stylefeng.guns.modular.basic.service.BasicCarrierService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.transport.entity.TDispatch;
import cn.stylefeng.guns.modular.transport.entity.TransportAuditProcess;
import cn.stylefeng.guns.modular.transport.entity.TransportCarrierFreight;
import cn.stylefeng.guns.modular.transport.entity.ZhuangyunMingxiTongji;
import cn.stylefeng.guns.modular.transport.model.params.TDispatchParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportAuditProcessParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportCarrierFreightParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportDispatchParam;
import cn.stylefeng.guns.modular.transport.service.TDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportAuditProcessService;
import cn.stylefeng.guns.modular.transport.service.TransportCarrierFreightService;
import cn.stylefeng.guns.modular.transport.service.TransportDispatchService;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/rec/carrierRecDetail")
public class CarrierRecDetailController {

    private String PREFIX = "/rec/carrierRecDetail";

    @Autowired
    private UserService userService;

    @Autowired
    private BasicOperateService basicOperateService;

    @Autowired
    private TransportDispatchService transportDispatchService;

    @Resource
    private RoleService roleService;

    @Autowired
    private BasicCarrierService basicCarrierService;

    @Autowired
    private TDispatchService tDispatchService;

    @Autowired
    private TransportCarrierFreightService transportFreightService;

    @Autowired
    private TransportAuditProcessService transportProcessService;

    /**
     * 跳转到 好想来TMS监控
     */
    @RequestMapping("")
    public String hx_totmsmonitor(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId, deliverId, user.getOperateId()));
        // 承运商
        BasicCarrierParam carrierParam = new BasicCarrierParam();
        carrierParam.setDeliverId(deliverId);
        carrierParam.setDeptId(deptId);
        carrierParam.setOperateId(user.getOperateId());
        List<BasicCarrierResult> carrierLists = basicCarrierService.findListBySpec(carrierParam, user.getOperateId());
        model.addAttribute("carrierLists", carrierLists);
        return PREFIX + "/carrierRecDetail.html";
    }

    // 时序图页面
    @RequestMapping("/tooTimeLine")
    public String tooTimeLine(TDispatchParam tDispatchParam) {
        return PREFIX + "/tooTimeLine.html";
    }

    @RequestMapping("/tooTimeLineDetailed")
    @ResponseBody
    public ResponseData tooTimeLineWeb(TransportAuditProcessParam transportA){

        QueryWrapper<TransportAuditProcess> wrapper = new QueryWrapper<>();
        wrapper.eq("dispatch_number", transportA.getDispatchNumber())
                .orderByAsc("review_time");
        List<TransportAuditProcess> list = transportProcessService.list(wrapper);

        return ResponseData.success(list);
    }

    /**
     * 查询分页
     * @param transportDispatchParam
     * @param condition
     * @param startTime
     * @param endTime
     * @param getUnit
     * @param operateId
     * @return
     */
    @ResponseBody
    @RequestMapping("/listPage")
    public LayuiPageInfo listPage(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        String roleId = user.getRoleId();
        if(ToolUtil.isNotEmpty(roleId)){
            for(String rId : roleId.split(",")){
                Role byId = roleService.getById(rId);
                if(byId != null && byId.getName().contains("承运商")){
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if(bySpec != null){
                        transportDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    }else{
                        transportDispatchParam.setCarrierName(user.getName());
                    }
                }
            }
        }
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        return this.transportDispatchService.findCarrierRecDetailPage(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
    }


    /**
     * 查询全部
     * @param transportDispatchParam
     * @param condition
     * @param startTime
     * @param endTime
     * @param getUnit
     * @param operateId
     * @return
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List<ZhuangyunMingxiTongji> listAll(TransportDispatchParam transportDispatchParam, String condition, String startTime, String endTime, String getUnit
            , Long operateId) {
        User user = userService.getcurrentUser();
        String roleId = user.getRoleId();
        if(ToolUtil.isNotEmpty(roleId)){
            for(String rId : roleId.split(",")){
                Role byId = roleService.getById(rId);
                if(byId != null && byId.getName().contains("承运商")){
                    BasicCarrierParam param = new BasicCarrierParam();
                    param.setUserId(user.getUserId());
                    BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
                    if(bySpec != null){
                        transportDispatchParam.setCarrierId(Long.valueOf(bySpec.getId()));
                    }else{
                        transportDispatchParam.setCarrierName(user.getName());
                    }
                }
            }
        }
        transportDispatchParam.setDeptId(user.getDeptId());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String times = "";
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            times = "'" + startTime + "' and '" + endTime + "'";
        } else if (startTime == null && endTime == null) {
            startTime = DateUtil.getDate();
            endTime = DateUtil.getDate();
            times = "'" + startTime + "' and '" + endTime + "'";
        }
        return this.transportDispatchService.findCarrierRecDetailAll(transportDispatchParam, condition, getUnit, times, operateId, user.getOperateId());
    }

    /**
     * 审核
     * @param transportFreightParam
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping("/audit")
    public ResponseData audit(TransportCarrierFreightParam transportFreightParam){
        User user = userService.getcurrentUser();
        // 1、根据dispatchNumber修改rec_state状态 ‘财务已审核’
        boolean updatedRows = tDispatchService.lambdaUpdate()
                .set(TDispatch::getRecState, "财务已审核")
                .eq(TDispatch::getDispatchNumber, transportFreightParam.getDispatchNumber())
                .eq(TDispatch::getRecState,"待审核")
                .update();

        if (!updatedRows) {
            return ResponseData.error("承运商明细[运输单号: " + transportFreightParam.getDispatchNumber() + "]的状态不是'待审核'，无法进行确认");
        }

        // 2、插入对账信息表
        TransportCarrierFreight transportF = new TransportCarrierFreight();
        transportF.setOperateId(transportFreightParam.getOperateId());
        transportF.setOperateName(transportFreightParam.getOperateName());
        transportF.setStartDate(transportFreightParam.getStartDate());
        transportF.setDispatchNumber(transportFreightParam.getDispatchNumber());
        transportF.setCarrierId(transportFreightParam.getCarrierId());
        transportF.setCarrierName(transportFreightParam.getCarrierName());
        transportF.setCarnumber(transportFreightParam.getCarnumber());
        transportF.setDriver1(transportFreightParam.getDriver1());
        transportF.setTel1(transportFreightParam.getTel1());
        transportF.setPrivatecarType(transportFreightParam.getPrivatecarType());
        transportF.setMileageTraveled(transportFreightParam.getMileageTraveled());
        transportF.setTotalVolume(transportFreightParam.getTotalVolume());
        transportF.setTotalPieces(transportFreightParam.getTotalPieces());
        transportF.setPieceNumberSum(transportFreightParam.getPieceNumberSum());
        transportF.setFreightMoney(transportFreightParam.getFreightMoney());
        transportF.setConsultMoney(transportFreightParam.getConsultMoney());
        transportF.setLoadingMoney(transportFreightParam.getLoadingMoney());
        transportF.setUnloadingMoney(transportFreightParam.getUnloadingMoney());
        transportF.setNotes(transportFreightParam.getNotes());
        transportF.setDeliverId(user.getDeliverId());
        transportF.setDeptId(user.getDeptId());
        transportF.setRecStatus("财务已审核");
        transportFreightService.save(transportF);
        // 3、插入流程信息表
        TransportAuditProcessParam transportP = new TransportAuditProcessParam();
        transportP.setOperateId(transportFreightParam.getOperateId());
        transportP.setOperateName(transportFreightParam.getOperateName());
        transportP.setDispatchNumber(transportFreightParam.getDispatchNumber());
        transportP.setRecStatus("财务已审核");
        transportP.setReview(user.getName());
        transportP.setReviewTime(new Date());
        transportP.setProcessRemark(transportFreightParam.getNotes());
        transportP.setCarrierFreightId(transportF.getId());
        transportProcessService.add(transportP);

        return ResponseData.success(200,"审核成功",null);
    }

    /**
     * 财务批量审核
     * @param auditDataList
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping("/batchAudit")
    public ResponseData batchAudit(@RequestBody List<TransportCarrierFreightParam> auditDataList) {
        User user = userService.getcurrentUser();

        // 1.检查信息
        for (TransportCarrierFreightParam transportF : auditDataList) {
            String dispatchNumber = transportF.getDispatchNumber();
            QueryWrapper<TDispatch> tDispatchQueryWrapper = new QueryWrapper<>();
            tDispatchQueryWrapper.eq("dispatch_number", dispatchNumber);
            TDispatch t = tDispatchService.getOne(tDispatchQueryWrapper);
            if (!"待审核".equals(t.getRecState())) {
                return ResponseData.error("承运商明细中[订单号: " + dispatchNumber + "]的状态不是'待审核'，无法进行确认");
            }
        }

        // 2.修改内容
        for (TransportCarrierFreightParam transportF : auditDataList) {
            // 1、修改t表
            tDispatchService.lambdaUpdate()
                    .set(TDispatch::getRecState, "财务已审核")
                    .eq(TDispatch::getDispatchNumber, transportF.getDispatchNumber())
                    .eq(TDispatch::getRecState, "待审核")
                    .update();

            // 2、插入c表
            TransportCarrierFreight transportFEntity = new TransportCarrierFreight();
            transportFEntity.setOperateId(transportF.getOperateId());
            transportFEntity.setOperateName(transportF.getOperateName());
            transportFEntity.setStartDate(transportF.getStartDate());
            transportFEntity.setDispatchNumber(transportF.getDispatchNumber());
            transportFEntity.setCarrierId(transportF.getCarrierId());
            transportFEntity.setCarrierName(transportF.getCarrierName());
            transportFEntity.setCarnumber(transportF.getCarnumber());
            transportFEntity.setDriver1(transportF.getDriver1());
            transportFEntity.setTel1(transportF.getTel1());
            transportFEntity.setPrivatecarType(transportF.getPrivatecarType());
            transportFEntity.setMileageTraveled(transportF.getMileageTraveled());
            transportFEntity.setTotalVolume(transportF.getTotalVolume());
            transportFEntity.setTotalPieces(transportF.getTotalPieces());
            transportFEntity.setPieceNumberSum(transportF.getPieceNumberSum());
            transportFEntity.setFreightMoney(transportF.getFreightMoney());
            transportFEntity.setConsultMoney(transportF.getConsultMoney());
            transportFEntity.setLoadingMoney(transportF.getLoadingMoney());
            transportFEntity.setUnloadingMoney(transportF.getUnloadingMoney());
            transportFEntity.setNotes(transportF.getNotes());
            transportFEntity.setDeliverId(user.getDeliverId());
            transportFEntity.setDeptId(user.getDeptId());
            transportFEntity.setRecStatus("财务已审核");
            transportFreightService.save(transportFEntity);

            // 3、插入流程信息表
            TransportAuditProcessParam transportP = new TransportAuditProcessParam();
            transportP.setOperateId(transportF.getOperateId());
            transportP.setOperateName(transportF.getOperateName());
            transportP.setDispatchNumber(transportF.getDispatchNumber());
            transportP.setRecStatus("财务已审核");
            transportP.setReview(user.getName());
            transportP.setReviewTime(new Date());
            transportP.setProcessRemark(transportF.getNotes());
            transportP.setCarrierFreightId(transportFEntity.getId());
            transportProcessService.add(transportP);
        }

        return ResponseData.success(200, "审核成功", null);
    }

    /**
     * 承运商确认
     * @param transportF
     * @return
     */
    @Transactional
    @RequestMapping("/confirm")
    @ResponseBody
    public ResponseData confirm(TransportCarrierFreightParam transportF){
        User user = userService.getcurrentUser();
        // 修改t状态
        boolean updateT = tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber, transportF.getDispatchNumber())
                .eq(TDispatch::getRecState, "财务已审核")
                .set(TDispatch::getRecState, "承运商已确认")
                .update();
        if (!updateT){
            return ResponseData.error("承运商明细中[订单号: " + transportF.getDispatchNumber() + "]的状态不是'财务已审核'，无法进行确认");
        }
        // 修改c状态
        boolean updateC = transportFreightService.lambdaUpdate()
                .eq(TransportCarrierFreight::getId, transportF.getId())
                .eq(TransportCarrierFreight::getRecStatus, "财务已审核")
                .set(TransportCarrierFreight::getRecStatus, "承运商已确认")
                .set(TransportCarrierFreight::getNotes, transportF.getNotes())
                .update();
        if (!updateC){
            return ResponseData.error("承运商明细中[订单号: " + transportF.getDispatchNumber() + "]的状态不是'财务已审核'，无法进行确认");
        }

        // 流程记录
        TransportAuditProcessParam transportP = new TransportAuditProcessParam();
        transportP.setOperateId(transportF.getOperateId());
        transportP.setOperateName(transportF.getOperateName());
        transportP.setDispatchNumber(transportF.getDispatchNumber());
        transportP.setRecStatus("承运商已确认");
        transportP.setReview(user.getName());
        transportP.setReviewTime(new Date());
        transportP.setProcessRemark(transportF.getNotes());
        transportP.setCarrierFreightId(transportF.getId());
        transportProcessService.add(transportP);

        return ResponseData.success(200, "承运商确认成功", null);
    }

    /**
     * 承运商批量确认
     * @param ids
     * @param value
     * @return
     */
    @Transactional
    @RequestMapping("/btnConfirm")
    @ResponseBody
    public ResponseData btnConfirm(@RequestParam("ids") Long[] ids, @RequestParam("value") String value){
        User user = userService.getcurrentUser();
        // 1.for查询是否有错误的订单
        for(Long id : ids){
            // 1.1、c表状态
            TransportCarrierFreight c = transportFreightService.getById(id);
            String dispatchNumber = c.getDispatchNumber();
            if (!"财务已审核".equals(c.getRecStatus())) {
                return ResponseData.error("记录[运输单号: " + dispatchNumber + "]的状态不是'财务已审核'，无法进行确认");
            }
            // 1.2、t表状态
            QueryWrapper<TDispatch> tDispatchQueryWrapper = new QueryWrapper<>();
            tDispatchQueryWrapper.eq("dispatch_number", dispatchNumber);
            TDispatch t = tDispatchService.getOne(tDispatchQueryWrapper);
            if (!"财务已审核".equals(t.getRecState())) {
                return ResponseData.error("承运商明细中[订单号: " + dispatchNumber + "]的状态不是'财务已审核'，无法进行确认");
            }
        }

        // 2.for循环修改记录
        for (Long id : ids){
            // 2.1、c表
            TransportCarrierFreight cTable = new TransportCarrierFreight();
            cTable.setId(Math.toIntExact(id));
            cTable.setRecStatus("承运商已确认");
            transportFreightService.updateById(cTable);
            // 2.2、修改t表
            TransportCarrierFreight c = transportFreightService.getById(id);
            String dispatchNumber = c.getDispatchNumber();
            tDispatchService.lambdaUpdate()
                    .eq(TDispatch::getDispatchNumber, dispatchNumber)
                    .eq(TDispatch::getRecState, "财务已审核")
                    .set(TDispatch::getRecState, "承运商已确认")
                    .update();
            // 2.3、插入流程记录
            TransportAuditProcessParam transportP = new TransportAuditProcessParam();
            transportP.setOperateId(c.getOperateId());
            transportP.setOperateName(c.getOperateName());
            transportP.setDispatchNumber(c.getDispatchNumber());
            transportP.setRecStatus("承运商已确认");
            transportP.setReview(user.getName());
            transportP.setReviewTime(new Date());
            transportP.setProcessRemark(value);
            transportP.setCarrierFreightId(c.getId());
            transportProcessService.add(transportP);
        }
        return ResponseData.success(200, "已确认成功！",null);
    }


    /**
     * 财务批量确认
     * @param ids
     * @param value
     * @return
     */
    @Transactional
    @RequestMapping("/btnReconfirm")
    @ResponseBody
    public ResponseData btnReconfirm(@RequestParam("ids") Long[] ids, @RequestParam("value") String value){
        User user = userService.getcurrentUser();
        // 1.for查询是否有错误的订单
        for(Long id : ids){
            // 1.1、c表状态
            TransportCarrierFreight c = transportFreightService.getById(id);
            String dispatchNumber = c.getDispatchNumber();
            if (!"承运商已确认".equals(c.getRecStatus())) {
                return ResponseData.error("记录[运输单号: " + dispatchNumber + "]的状态不是'承运商已确认'，无法进行确认");
            }
            // 1.2、t表状态
            QueryWrapper<TDispatch> tDispatchQueryWrapper = new QueryWrapper<>();
            tDispatchQueryWrapper.eq("dispatch_number", dispatchNumber);
            TDispatch t = tDispatchService.getOne(tDispatchQueryWrapper);
            if (!"承运商已确认".equals(t.getRecState())) {
                return ResponseData.error("承运商明细中[订单号: " + dispatchNumber + "]的状态不是'承运商已确认'，无法进行确认");
            }
        }

        // 2.for循环修改记录
        for (Long id : ids){
            // 2.1、c表
            TransportCarrierFreight cTable = new TransportCarrierFreight();
            cTable.setId(Math.toIntExact(id));
            cTable.setRecStatus("财务已确定");
            transportFreightService.updateById(cTable);
            // 2.2、修改t表
            TransportCarrierFreight c = transportFreightService.getById(id);
            String dispatchNumber = c.getDispatchNumber();
            tDispatchService.lambdaUpdate()
                    .eq(TDispatch::getDispatchNumber, dispatchNumber)
                    .eq(TDispatch::getRecState, "承运商已确认")
                    .set(TDispatch::getRecState, "财务已确定")
                    .update();
            // 2.3、插入流程记录
            TransportAuditProcessParam transportP = new TransportAuditProcessParam();
            transportP.setOperateId(c.getOperateId());
            transportP.setOperateName(c.getOperateName());
            transportP.setDispatchNumber(c.getDispatchNumber());
            transportP.setRecStatus("财务已确定");
            transportP.setReview(user.getName());
            transportP.setReviewTime(new Date());
            transportP.setProcessRemark(value);
            transportP.setCarrierFreightId(c.getId());
            transportProcessService.add(transportP);
        }
        return ResponseData.success(200, "已确认成功！",null);
    }

    /**
     * 财务批量撤回
     * @param ids
     * @param value
     * @return
     */
    @Transactional
    @RequestMapping("/btnRetract")
    @ResponseBody
    public ResponseData btnRetract(@RequestParam("ids") Long[] ids, @RequestParam("value") String value){
        User user = userService.getcurrentUser();
        // 1.for查询是否有错误的订单
        for(Long id : ids){
            // 1.1、c表状态
            TransportCarrierFreight c = transportFreightService.getById(id);
            String dispatchNumber = c.getDispatchNumber();
            if (!"财务已审核".equals(c.getRecStatus())) {
                return ResponseData.error("记录[运输单号: " + dispatchNumber + "]的状态不是'财务已审核'，无法进行确认");
            }
            // 1.2、t表状态
            QueryWrapper<TDispatch> tDispatchQueryWrapper = new QueryWrapper<>();
            tDispatchQueryWrapper.eq("dispatch_number", dispatchNumber);
            TDispatch t = tDispatchService.getOne(tDispatchQueryWrapper);
            if (!"财务已审核".equals(t.getRecState())) {
                return ResponseData.error("承运商明细中[订单号: " + dispatchNumber + "]的状态不是'财务已审核'，无法进行确认");
            }
        }

        // 2.for循环修改记录
        for (Long id : ids){
            // 2.1、c表
            TransportCarrierFreight cTable = new TransportCarrierFreight();
            cTable.setId(Math.toIntExact(id));
            cTable.setRecStatus("待审核");
            transportFreightService.updateById(cTable);
            // 2.2、修改t表
            TransportCarrierFreight c = transportFreightService.getById(id);
            String dispatchNumber = c.getDispatchNumber();
            tDispatchService.lambdaUpdate()
                    .eq(TDispatch::getDispatchNumber, dispatchNumber)
                    .eq(TDispatch::getRecState, "财务已审核")
                    .set(TDispatch::getRecState, "待审核")
                    .update();
            // 2.3、插入流程记录
            TransportAuditProcessParam transportP = new TransportAuditProcessParam();
            transportP.setOperateId(c.getOperateId());
            transportP.setOperateName(c.getOperateName());
            transportP.setDispatchNumber(c.getDispatchNumber());
            transportP.setRecStatus("财务已撤回");
            transportP.setReview(user.getName());
            transportP.setReviewTime(new Date());
            transportP.setProcessRemark(value);
            transportP.setCarrierFreightId(c.getId());
            transportProcessService.add(transportP);
        }
        return ResponseData.success(200, "已确认成功！",null);
    }

    /**
     * 财务最后确认
     * @param transportF
     * @return
     */
    @Transactional
    @RequestMapping("/Reconfirm")
    @ResponseBody
    public ResponseData Reconfirm(TransportCarrierFreightParam transportF) {
        User user = userService.getcurrentUser();
        // 修改t状态
        boolean updateT = tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber, transportF.getDispatchNumber())
                .eq(TDispatch::getRecState, "承运商已确认")
                .set(TDispatch::getRecState, "财务已确定")
                .update();
        if (!updateT) {
            return ResponseData.error("承运商明细[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'承运商已确认'，无法进行确认");
        }
        // 修改c状态
        boolean updateC = transportFreightService.lambdaUpdate()
                .eq(TransportCarrierFreight::getId, transportF.getId())
                .eq(TransportCarrierFreight::getRecStatus, "承运商已确认")
                .set(TransportCarrierFreight::getRecStatus, "财务已确定")
                .set(TransportCarrierFreight::getNotes, transportF.getNotes())
                .update();
        if (!updateC) {
            return ResponseData.error("记录[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'承运商已确认'，无法进行确认");
        }
        // 流程记录
        TransportAuditProcessParam transportP = new TransportAuditProcessParam();
        transportP.setOperateId(transportF.getOperateId());
        transportP.setOperateName(transportF.getOperateName());
        transportP.setDispatchNumber(transportF.getDispatchNumber());
        transportP.setRecStatus("财务已确定");
        transportP.setReview(user.getName());
        transportP.setReviewTime(new Date());
        transportP.setProcessRemark(transportF.getNotes());
        transportP.setCarrierFreightId(transportF.getId());
        transportProcessService.add(transportP);

        return ResponseData.success(200, "已确认成功！",null);
    }

    /**
     * 财务撤回
     * @param transportF
     * @return
     */
    @Transactional
    @RequestMapping("/retract")
    @ResponseBody
    public ResponseData retract(TransportCarrierFreightParam transportF) {
        User user = userService.getcurrentUser();
        // 修改t状态
        tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber, transportF.getDispatchNumber())
                .set(TDispatch::getRecState, "待审核")
                .update();
        // 修改c状态
        transportFreightService.lambdaUpdate()
                .eq(TransportCarrierFreight::getId, transportF.getId())
                .set(TransportCarrierFreight::getRecStatus, "待审核")
                .set(TransportCarrierFreight::getNotes, transportF.getNotes())
                .update();
        // 流程记录
        TransportAuditProcessParam transportP = new TransportAuditProcessParam();
        transportP.setOperateId(transportF.getOperateId());
        transportP.setOperateName(transportF.getOperateName());
        transportP.setDispatchNumber(transportF.getDispatchNumber());
        transportP.setRecStatus("财务已撤回");
        transportP.setReview(user.getName());
        transportP.setReviewTime(new Date());
        transportP.setProcessRemark(transportF.getNotes());
        transportP.setCarrierFreightId(transportF.getId());
        transportProcessService.add(transportP);

        return ResponseData.success(200, "已撤回成功！",null);
    }

    /**
     * 承运商申诉
     * @param transportF
     * @return
     */
    @Transactional
    @RequestMapping("/complaint")
    @ResponseBody
    public ResponseData complaint(TransportCarrierFreightParam transportF) {
        User user = userService.getcurrentUser();
        // 修改t状态
        boolean updateT = tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber, transportF.getDispatchNumber())
                .eq(TDispatch::getRecState, "财务已审核")
                .set(TDispatch::getRecState, "申诉待解决")
                .update();
        if (!updateT) {
            return ResponseData.error("承运商明细[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'财务已审核'，无法进行申诉");
        }
        // 修改c状态
        boolean updateC = transportFreightService.lambdaUpdate()
                .eq(TransportCarrierFreight::getId, transportF.getId())
                .eq(TransportCarrierFreight::getRecStatus, "财务已审核")
                .set(TransportCarrierFreight::getRecStatus, "申诉待解决")
                .set(TransportCarrierFreight::getNotes, transportF.getNotes())
                .update();
        if (!updateC) {
            return ResponseData.error("记录[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'财务已审核'，无法进行申诉");
        }
        // 流程记录
        TransportAuditProcessParam transportP = new TransportAuditProcessParam();
        transportP.setOperateId(transportF.getOperateId());
        transportP.setOperateName(transportF.getOperateName());
        transportP.setDispatchNumber(transportF.getDispatchNumber());
        transportP.setRecStatus("申诉待解决");
        transportP.setReview(user.getName());
        transportP.setReviewTime(new Date());
        transportP.setProcessRemark(transportF.getNotes());
        transportP.setCarrierFreightId(transportF.getId());
        transportProcessService.add(transportP);

        return ResponseData.success(200, "已申诉成功！",null);
    }

    /**
     * 财务已提报-OA
     * @param transportF
     * @return
     */
    @Transactional
    @RequestMapping("/generate")
    @ResponseBody
    public ResponseData generate(TransportCarrierFreightParam transportF) {
        // TODO 财务已提报-OA
        return ResponseData.success();
    }

    /**
     * 承运商撤回申诉
     * @param transportF
     * @return
     */
    @Transactional
    @RequestMapping("/carrierRetract")
    @ResponseBody
    public ResponseData carrierRetract(TransportCarrierFreightParam transportF) {
        User user = userService.getcurrentUser();
        // 修改t状态
        boolean updateT = tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber, transportF.getDispatchNumber())
                .eq(TDispatch::getRecState, "申诉待解决")
                .set(TDispatch::getRecState, "财务已审核")
                .update();
        if (!updateT) {
            return ResponseData.error("承运商明细[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'申诉待解决'，无法进行申诉");
        }
        // 修改c状态
        boolean updateC = transportFreightService.lambdaUpdate()
                .eq(TransportCarrierFreight::getId, transportF.getId())
                .eq(TransportCarrierFreight::getRecStatus, "申诉待解决")
                .set(TransportCarrierFreight::getRecStatus, "财务已审核")
                .set(TransportCarrierFreight::getNotes, transportF.getNotes())
                .update();
        if (!updateC) {
            return ResponseData.error("记录[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'申诉待解决'，无法进行申诉");
        }

        // 流程记录
        TransportAuditProcessParam transportP = new TransportAuditProcessParam();
        transportP.setOperateId(transportF.getOperateId());
        transportP.setOperateName(transportF.getOperateName());
        transportP.setDispatchNumber(transportF.getDispatchNumber());
        transportP.setRecStatus("承运商已撤回申诉");
        transportP.setReview(user.getName());
        transportP.setReviewTime(new Date());
        transportP.setProcessRemark(transportF.getNotes());
        transportP.setCarrierFreightId(transportF.getId());
        transportProcessService.add(transportP);
        return ResponseData.success(200, "已撤回成功！",null);
    }


    /**
     * 财务撤回承运商申诉
     * @param transportF
     * @return
     */
    @Transactional
    @RequestMapping("/financeRetract")
    @ResponseBody
    public ResponseData financeRetract(TransportCarrierFreightParam transportF) {
        User user = userService.getcurrentUser();
        // 1.根据货运订单号获取最新数据
        TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
        transportDispatchParam.setDispatchNumber(transportF.getDispatchNumber());
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        List<ZhuangyunMingxiTongji> carrierRecDetailAll = transportDispatchService.findCarrierRecDetailAll(transportDispatchParam, "", "", "", null, user.getOperateId());
        ZhuangyunMingxiTongji t = carrierRecDetailAll.get(0);

        // 修改t状态
        boolean updateT = tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber, transportF.getDispatchNumber())
                .eq(TDispatch::getRecState, "申诉待解决")
                .set(TDispatch::getRecState, "财务已审核")
                .update();
        if(!updateT) {
            return ResponseData.error("记录[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'财务已审核'，无法进行确认");
        }

        // 更新c表
        boolean updateC = transportFreightService.lambdaUpdate()
                .eq(TransportCarrierFreight::getId, transportF.getId())
                .eq(TransportCarrierFreight::getRecStatus, "申诉待解决")
                .set(TransportCarrierFreight::getRecStatus, "财务已审核")
                .set(TransportCarrierFreight::getOperateId, t.getOperateId())
                .set(TransportCarrierFreight::getOperateName, t.getOperateName())
                .set(TransportCarrierFreight::getStartDate, t.getStartDate())
                .set(TransportCarrierFreight::getCarrierId, t.getCarrierId())
                .set(TransportCarrierFreight::getCarrierName, t.getCarrierName())
                .set(TransportCarrierFreight::getCarnumber, t.getCarnumber())
                .set(TransportCarrierFreight::getDriver1, t.getDriver1())
                .set(TransportCarrierFreight::getTel1, t.getTel1())
                .set(TransportCarrierFreight::getPrivatecarType, t.getPrivatecarType())
                .set(TransportCarrierFreight::getMileageTraveled, t.getMileageTraveled())
                .set(TransportCarrierFreight::getTotalVolume, t.getToovolume())
                .set(TransportCarrierFreight::getTotalPieces, t.getMatrixingNumberSum())
                .set(TransportCarrierFreight::getPieceNumberSum, t.getPieceNumberSum())
                .set(TransportCarrierFreight::getFreightMoney, t.getFreightMoney())
                .set(TransportCarrierFreight::getConsultMoney, t.getConsultMoney())
                .set(TransportCarrierFreight::getLoadingMoney, t.getLoadingMoney())
                .set(TransportCarrierFreight::getUnloadingMoney, t.getXiechefei())
                .set(TransportCarrierFreight::getNotes, transportF.getNotes())
                .update();
        if (!updateC){
            return ResponseData.error("记录[运输单号: " + transportF.getDispatchNumber() + "]的状态不是'承运商已审核'，无法进行确认");
        }

        // 流程记录
        TransportAuditProcessParam transportP = new TransportAuditProcessParam();
        transportP.setOperateId(transportF.getOperateId());
        transportP.setOperateName(transportF.getOperateName());
        transportP.setDispatchNumber(transportF.getDispatchNumber());
        transportP.setRecStatus("已更正数据，重新提起审核");
        transportP.setReview(user.getName());
        transportP.setReviewTime(new Date());
        transportP.setProcessRemark(transportF.getNotes());
        transportP.setCarrierFreightId(transportF.getId());
        transportProcessService.add(transportP);
        return ResponseData.success(200, "确认成功", "");
    }


    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 承运商申诉
    @GetMapping("/complaintCount")
    @ResponseBody
    public int complaintCount() {
        String sql = "SELECT COUNT(*) AS count FROM transport_carrier_freight where rec_status = '申诉待解决'";
        int count = jdbcTemplate.queryForObject(sql, (rs, rowNum) -> rs.getInt("count"));
        return count;
    }


}
